<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Structures in C#</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, learn C#, structures, .NET, Mono, programming, language, tutorial">
<meta name="description" content="This part of the C# tutorial covers C# structures.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Structures</h1>

<p>
In this part of the C# tutorial, we will cover structures.
</p>

<p>
A structure is a value type. The type is defined with the 
<code>struct</code> keyword. Structures are very similar to 
the classes; they differ in some aspects. Structures are meant
to represent lightweight objects like Point, Rectangle, Color
and similar. In many cases, structures may be more efficient
than classes. Structures are value types and are created on the
stack. Note that primitive data types like int, bool, float are
technically struct types. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
Structures can have constructors. They can contain data members and
methods. They also can implement interfaces.
</p>

<p>
All struct types inherit from <b class="keyword">System.ValueType</b>. 
And further from <b class="keyword">object</b>. Structures are never 
abstract and they are always implicitly sealed. So struct types do not 
support inheritance. And therefore, the struct data member cannot be 
declared  protected. The abstract and sealed modifiers are not 
permitted for a struct definition. A struct is not permitted to declare 
a parameterless constructor. 
</p>


<pre class="code">
using System;


public struct Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override string ToString()
    {
        return String.Format("Point, x:{0}, y:{1}", x, y);
    }
}


public class CSharpApp
{
    static void Main()
    {
        Point p = new Point(2, 5);
        Console.WriteLine(p);        
    }
}
</pre>

<p>
We have a simple example demonstrating the struct type. 
We create a Point struct. The point could be represented
by a class too, but with struct we are more efficient. Especially
if we dealt with lots of points. 
</p>

<pre class="explanation">
public struct Point
{
    ...
}
</pre>

<p>
The structure is declared with the <code>struct</code> keyword. 
</p>

<pre class="explanation">
public override string ToString()
{
    return String.Format("Point, x:{0}, y:{1}", x, y);
}
</pre>

<p>
The inheritance is not supported for struct types. But we can
use the <code>override</code> keyword for methods, from which 
the struct type implicitly inherits. The <code>ToString()</code> 
method is such a case. 
</p>

<pre class="explanation">
Point p = new Point(2, 5);
Console.WriteLine(p);   
</pre>

<p>
We create the Point structure and call the <code>ToString()</code> method
upon it. 
</p>

<pre>
$ ./simple.exe 
Point, x:2, y:5
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
It is possible to create an instance of the struct type without
the <code>new</code> keyword. 
</p>

<pre class="code">
using System;


public struct Person 
{
    public string name; 
    public int age;
}

public class CSharpApp
{
    static void Main()
    {
        Person p;
        p.name = "Jane";
        p.age = 17;

        Console.WriteLine("{0} is {1} years old", 
            p.name, p.age);        
    }
}
</pre>

<p>
We have a Person structure with two public members. 
</p>


<pre class="explanation">
Person p;
</pre>

<p>
First we declare a Person struct.
</p>

<pre class="explanation">
p.name = "Jane";
p.age = 17;
</pre>

<p>
Later we initialize the structure with some data. 
</p>

<pre>
$ ./properties.exe 
Jane is 17 years old
</pre>

<p>
Output. 
</p>

<hr class="btm">

<p>
<b>Structures are value types</b> The structure types are value types. 
They are created on the stack. When a value type is created only 
a single space in memory is allocated to store the value. An assignment
of a value type copies the value. 
</p>

<pre class="code">
using System;


public struct Person 
{
    public Person(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }

    public string Name { get; set; }

    public int Age { get; set; }

    public override string ToString()
    {
        return String.Format("{0} is {1} years old", Name, Age);
    }
}


public class CSharpApp
{
    static void Main()
    {
        Person p1 = new Person("Beky", 18);
        Person p2 = p1;

        Console.WriteLine(p2); 
        p2.Name = "Jane";
        p2.Age = 17;

        Console.WriteLine(p2); 
        Console.WriteLine(p1);           
    }
}
</pre>

<p>
We have a Person structure with two data members. We have a
two parameter constructor and we also use automatic properties. 
</p>

<pre class="explanation">
public string Name { get; set; }
public int Age { get; set; }
</pre>

<p>
Automatic properties can be used in struct types. 
</p>

<pre class="explanation">
Person p1 = new Person("Beky", 18);
Person p2 = p1;
</pre>

<p>
Here we create a struct. And then the created struct is
assigned to another struct. We create a copy of the structure. 
</p>

<pre class="explanation">
p2.Name = "Jane";
p2.Age = 17;
</pre>

<p>
We change the data of the second structure. The first one is not
affected, since we work on the copy of the original struct type. 
</p>

<pre>
$ ./valuetype.exe 
Beky is 18 years old
Jane is 17 years old
Beky is 18 years old
</pre>

<p>
Output. 
</p>

<hr class="btm">

<p>
<b>Primitive types are structures</b> The primitive data types like
int, float or bool are structures under the hood. This differs from 
languages like C++ or Java. We will have an example demonstrating this. 
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        float x = 12.3f;
        int y = 34;
        bool z = false;

        Console.WriteLine(x.GetType());
        Console.WriteLine(y.GetType());
        Console.WriteLine(z.GetType());
    }
}
</pre>

<p>
We have three variables. A float an int and a bool.
We call the GetType() method on each of them. 
</p>

<pre class="explanation">
Console.WriteLine(x.GetType());
</pre>

<p>
We call the <code>GetType()</code> method on the float value. Each structure
implicitly inherits from the System.ValueType class, which contains
the <code>GetType()</code> method. 
</p>

<pre>
$ ./primitivetypes.exe 
System.Single
System.Int32
System.Boolean
</pre>

<p>
Output. 
</p>

<p>
In this part of the C# tutorial, we mentioned structures. 
</p>

<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified November 8, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div> <!-- footer -->

</div> <!-- content -->

</div> <!-- container -->

</body> 
</html>

